﻿using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using System.ComponentModel.DataAnnotations.Schema;
using ConsoleApp1.TypeConverters;

namespace Sample.ConsoleApp.CodeFist.Sqlite.Entitys;

/// <summary>
/// 实体对象
/// </summary>
internal class MyEntity
{
    public string Id { get; set; } = Guid.NewGuid().ToString();

    public int RandomNo { get; set; }

    [Column(TypeName = "json")]
    public JsonDocument Data { get; set; } = JsonDocument.Parse("{ }");

    [Column(TypeName = "text")]
    public DateTime CreatedTime { get; set; }
}

/// <summary>
/// 实体类型定义
/// </summary>
internal class MyEntityTypeConfiguration : IEntityTypeConfiguration<MyEntity>
{
    public void Configure(EntityTypeBuilder<MyEntity> entity)
    {
        entity.ToTable(nameof(MyEntity)); // 指定表名为 "Artifact"
        entity.HasKey(a => a.Id); // 指定主键：PK

        entity.Property(p => p.Id)
               .HasColumnName("Id")
               .HasColumnType("TEXT")
               .HasMaxLength(36)
               .IsRequired();

        entity.Property(p => p.RandomNo)
              .HasColumnName("RandomNo")
              .HasColumnType("INTEGER")
              .IsRequired();

        entity.Property(a => a.Data)
              .HasConversion(new JsonDocumentToStringConverter())
              .HasColumnName("Data")
              .HasColumnType("JSON")
              .IsRequired();

        entity.Property(a => a.CreatedTime)
             .HasConversion(new DateTimeToStringConverter())
             .HasColumnName("CreatedTime")
             .HasColumnType("TEXT")
             .HasMaxLength(16)
             .IsRequired();
    }
}
